package controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;

import org.springframework.web.multipart.MultipartFile;

import dao.ArchiveDao;
import dao.LogDao;
import service.ArchiveService;
import service.LogService;
import util.MybatisSessionFactory;

@Controller
public class Archive {
	
     //添加档案
	@RequestMapping(value = "/add.action", method = RequestMethod.POST)
	@ResponseBody
	public String add(
			@CookieValue(value = "user", defaultValue = "") String userId,
			@RequestParam(value = "archive_id", defaultValue = "") String archive_id,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "birthday", defaultValue = "") String birthday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "") String sp,
			@RequestParam(value = "fc", defaultValue = "") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority) {
		// System.out.println("archive_id");
		ArchiveService service = new ArchiveService();
		pojo.Archive result = service.queryone(archive_id, identity);

		if ("1".equals(result.getId())) {
			return "ERR";
		}
		service.add(archive_id, identity, name, gender, birthday, date_retire1,
				date_retire2, sp, fc, title, seniority);
		LogService service2 = new LogService();
		String a = service.LastId().get("archive_id").toString();
		// System.out.println(a);
		service2.insert(userId, a, "添加档案");
		return "OK";
	}
    
	//模糊查询
	@RequestMapping(value = "/chaxun.action", method = RequestMethod.POST)
	@ResponseBody
	public List<Map<String, Object>> chaxun(
			@CookieValue(value = "user", defaultValue = "") String userId,
			@RequestParam(value = "archive_id", defaultValue = "") String archive_id,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "birthday", defaultValue = "") String birthday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "") String sp,
			@RequestParam(value = "fc", defaultValue = "") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
			HttpServletResponse response) {
		// System.out.println(archive_id);
		ArchiveService service = new ArchiveService();
		List<Map<String, Object>> result = service.chaxun(archive_id, identity,
				name, gender, birthday, date_retire1, date_retire2, sp, fc,
				title, seniority);
		// Cookie cookie = new Cookie("query",
		// result.get(0).get("archive_id").toString());
		// response.addCookie(cookie);
		LogService service2 = new LogService();

		service2.insert(userId, result.get(0).get("archive_id").toString()
				.toString(), "查询档案");
		return result;
	}
    
	//搜索栏查询
	@RequestMapping(value = "/chaxun2.action", method = RequestMethod.POST)
	@ResponseBody
	public String chaxun2(
			@CookieValue(value = "user", defaultValue = "") String userId,
			@RequestParam(value = "a", defaultValue = "") String a) {
		System.out.println("a");
		ArchiveService service = new ArchiveService();
		pojo.Archive result = service.chaxun2(a);
		int i = Integer.valueOf(result.getCounter());
		if (i > 1) {
			return "ERR";
		} else if (i == 0) {
			return "ERR1";
		}
		System.out.println("00000000000000000");
		String id = result.getId();
		LogService service2 = new LogService();
		// System.out.println(result.getArchive_id());
		service2.insert(userId, result.getArchive_id().toString(), "查询档案");
		return id;
	}
     
	  //查询
	@RequestMapping(value = "/chaxun3.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String, Object>> chaxun3(
			@RequestParam(value = "id", defaultValue = "") String id) {
		ArchiveService service = new ArchiveService();
		// System.out.println(id);
		List<Map<String, Object>> result = service.chaxun3(id);
		// System.out.println(id);
		return result;
	}
      
	//修改
	@RequestMapping(value = "/update.action", method = RequestMethod.POST)
	@ResponseBody
	public String update(String id, String userId, String archive_id,
			String identity, String name, String gender, String birthday,
			String date_retire1, String date_retire2, String sp, String fc,
			String title, String seniority) {
		ArchiveService service = new ArchiveService();
		service.update(id, archive_id, identity, name, gender, birthday,
				date_retire1, date_retire2, sp, fc, title, seniority);
		LogService service2 = new LogService();

		service2.insert(userId, service.LastId().toString(), "修改档案");
		return "OK";
	}
    
	 //查询用户名
	@RequestMapping(value = "/user.action", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> querynickname(
			@CookieValue(value = "user", defaultValue = "") String userId,
			HttpServletResponse response) {
		ArchiveService service = new ArchiveService();
		Map<String, Object> map = service.querynickname(userId);

		return map;
	}
    
	//退出
	@RequestMapping(value = "/exit.action", method = RequestMethod.POST)
	@ResponseBody
	public String exit(
			@CookieValue(value = "user", defaultValue = "") String userId,
			HttpServletResponse response) {

		LogService service2 = new LogService();

		service2.insert(userId, "0", "退出");
		Cookie cooki = new Cookie("user", null);
		response.addCookie(cooki);
		return "OK";
	}
    
	//上传档案
	@RequestMapping(value = "/{id}/upload.action", method = RequestMethod.POST)
	@ResponseBody
	public String upload(
			@CookieValue(value = "user", defaultValue = "") String userId,
			@PathVariable String id, @RequestParam("file") MultipartFile file,
			HttpServletRequest req) {
		if (file.isEmpty()) {
			System.out.println("未选择文件");
			return "ERROR_NO_FILE";
		}
		try {
			byte[] bytes = file.getBytes();
			String fileName = file.getOriginalFilename();
			String fileExtension = fileName
					.substring(fileName.lastIndexOf(".") + 1);
			String newFileName = String.valueOf(System.currentTimeMillis())
					+ "." + fileExtension;
			// SqlSession session = factory.getSessionFactory().openSession();
			// ArchiveDao dao = session.getMapper(ArchiveDao.class);
			ArchiveService service = new ArchiveService();
			Map<String, Object> archive = service.info(id);
			String filePath = String.format("%s\\%s\\%s\\%s", req.getSession()
					.getServletContext().getRealPath("/"), "upload", archive
					.get("archive_id").toString(),
			// "1111",
					newFileName);
			File existsFile = new File(filePath);
			if (!existsFile.getParentFile().exists()) {
				if (!existsFile.getParentFile().mkdirs()) {
					System.out.println("创建目录失败");
					return "ERROR_ON_MKDIR";
				}
			}
			if (existsFile.exists()) {
				if (existsFile.delete()) {
					// System.out.println("删除原始文件：" + filePath);
				} else {
					System.out.println("删除文件失败：" + filePath);
				}
			}
			BufferedOutputStream stream = new BufferedOutputStream(
					new FileOutputStream(new File(filePath)));
			stream.write(bytes);
			stream.close();
			Map<String, Object> a = service.queryaccount(userId);
			String b = a.get("account").toString();
			service.insertPages(b, newFileName);
			LogService service2 = new LogService();

			service2.insert(userId, archive.get("archive_id").toString(),
					"上传档案");
			// session.commit();
			return "OK";
		} catch (Exception e) {
			e.printStackTrace();
			return "ERROR";
		}
	}
    
	//查询上传的档案
	@RequestMapping(value = "/queryfile.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String, Object>> queryfile(
			@RequestParam(value = "id", defaultValue = "") String id) {
		ArchiveService service = new ArchiveService();
		List<Map<String, Object>> map = service.queryfile(id);

		return map;
	}
    
	//删除档案
	@RequestMapping(value = "/del.action", method = RequestMethod.POST)
	@ResponseBody
	public String del(@RequestParam(value = "id", defaultValue = "") String id

	) {
		ArchiveService service = new ArchiveService();
		service.del(id);
		return "OK";
	}
   
	//详细查询档案
	@RequestMapping(value = "/querytu.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String, Object>> querytu(
			@RequestParam(value = "id", defaultValue = "") String id,
			HttpServletRequest req) {
		ArchiveService service = new ArchiveService();
		List<Map<String, Object>> map = service.querytu(id);
		// System.out.println(map.get(0).get("name"));

		String fileName = map.get(0).get("name").toString();
		Map<String, Object> archive = service.info2(id);
		// System.out.println(archive);
		String filePath = String.format("%s\\%s\\%s\\%s", req.getSession()
				.getServletContext().getRealPath("/"), "upload",
				archive.get("archive_id").toString(), fileName);
		File existsFile = new File(filePath);
		System.out.println(filePath);
		if (existsFile.exists()) {
			if (existsFile.delete()) {
				System.out.println("删除原始文件：" + filePath);
			} else {
				System.out.println("删除文件失败：" + filePath);
			}
		}
		return map;
	}
    
	//统计
	@RequestMapping(value = "/tongji.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String, Object>> tongji(

	) {
		ArchiveService service = new ArchiveService();
		List<Map<String, Object>> list = service.tongji();
		return list;
	}
    
	//记录档案
	@RequestMapping(value = "/record.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String, Object>> record4(
			@CookieValue(value = "user", defaultValue = "") String userId) {
		ArchiveService service = new ArchiveService();
		List<Map<String, Object>> result = service.record(userId);
		// System.out.println(result);
		return result;
	}
    
	//添加档案
	@RequestMapping(value = "/tianjia.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String, Object>> tianjia(
			@CookieValue(value = "user", defaultValue = "") String userId) {
		ArchiveService service = new ArchiveService();
		List<Map<String, Object>> result = service.tianjia(userId);
		// System.out.println(result);
		return result;
	}
    
	//按日期查询档案
	@RequestMapping(value = "/chadate.action", method = RequestMethod.POST)
	@ResponseBody
	public List<Map<String, Object>> chadate(

	@RequestParam(value = "date1", defaultValue = "") String date1,
			@RequestParam(value = "date2", defaultValue = "") String date2) {
		// System.out.println("archive_id");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, 0);
		c.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
		String first = format.format(c.getTime());
		// System.out.println("第一天:"+first);

		// 获取当前月最后一天
		Calendar ca = Calendar.getInstance();
		ca.set(Calendar.DAY_OF_MONTH,
				ca.getActualMaximum(Calendar.DAY_OF_MONTH));
		String last = format.format(ca.getTime());
		// System.out.println("最后一天:"+last);
		ArchiveService service = new ArchiveService();
		// System.out.println("123"+date1);
		if (date1 == null || date1.equals("")) {
			date1 = first;
			// List<Map<String, Object>> result1 = service.chadate(date, date2);
			// return result1;
		}
		if (date2 == null || date2.equals("")) {
			date2 = last;
			// List<Map<String, Object>> result2 = service.chadate(date1, date);
			// return result2;
		}
		// if(date1==null||date1.equals("")&&date2==null||date2.equals("")){
		// System.out.println("23232323");
		// List<Map<String, Object>> result3 = service.chadate(first, last);
		// return result3;
		// }
		System.out.println("1" + date1 + "2" + date2);
		List<Map<String, Object>> result = service.chadate(date1, date2);
		return result;
	}

}
